package cn.lumora.core.controller;

import cn.lumora.core.dto.ApiResponse;
import cn.lumora.core.model.BaseEntity;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.IService;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

public abstract class BaseController<T extends BaseEntity, S extends IService<T>> implements ApplicationContextAware {
    protected S baseService;
    private ApplicationContext applicationContext;
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }

    @PostConstruct
    @SuppressWarnings("unchecked")
    public void initService() {
        // 获取泛型参数类型
        Type genericSuperclass = getClass().getGenericSuperclass();
        if (genericSuperclass instanceof ParameterizedType) {
            ParameterizedType parameterizedType = (ParameterizedType) genericSuperclass;
            Type[] actualTypeArguments = parameterizedType.getActualTypeArguments();
            if (actualTypeArguments.length >= 2) {
                Type serviceType = actualTypeArguments[1]; // S是第二个泛型参数
                Class<S> serviceClass = (Class<S>) serviceType;
                this.baseService = this.applicationContext.getBean(serviceClass);
            }
        } else {
            throw new IllegalStateException("子类必须明确指定泛型参数");
        }
    }

    @RequestMapping("/list")
    public ApiResponse<?> list(@RequestBody(required = false) T t) {
        return null;
    }

    @RequestMapping("/get")
    public ApiResponse<?> get(@RequestBody T t) {
        return ApiResponse.success(baseService.getOne(new QueryWrapper<T>(t)));
    }

    @RequestMapping("/add")
    public ApiResponse<?> add(@RequestBody T t, HttpServletRequest request) {
       return null;
    }

    @RequestMapping("/update")
    public ApiResponse<?> update(@RequestBody T t, HttpServletRequest request) {
        return null;
    }

    protected boolean updateById(T t) {
        return baseService.updateById(t);
    }


}
